﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MTEA.LIB;

namespace MTEA.WatchDog
{
    class MTWatchDog
    {
        public static readonly string Tag = "MTWatchDog";
        private Dictionary<IWatchable, ulong> watchs;

        public static readonly MTWatchDog Instance = new MTWatchDog();
        public MTWatchDog()
        {
            watchs = new Dictionary<IWatchable, ulong>();
        }

        public void Start()
        {
            Task task = Task.Factory.StartNew(() =>
            {
                MTLogcat.i(Tag, "Start");
                do
                {
                    lock (watchs)
                    {
                        for (int i = 0; i < watchs.Count; i++)
                        {
                            var key = watchs.Keys.ElementAt(i);
                            ulong lastToken = watchs[key];
                            ulong currentToken = key.GetCurrentToken();
                            if (lastToken != currentToken)
                            {
                                watchs[key] = currentToken;
                            }
                            else
                            {
                                MTLogcat.w(Tag, "{0} is dead", key.Name);
                            }
                            MTLogcat.i(Tag,"Watching {0} ", key.Name);
                        }
                    }
                    Thread.Sleep(1000*120);
                } while (true);
                //Console.WriteLine("MTWatchDog : Stop");
            });
        }

        public void AddWatchable(IWatchable watachable)
        {
            lock (watchs)
            {
                int count = watchs.Keys.Where(x => x == watachable).Count();
                Debug.Assert(count == 0);
                //Random random = new Random((int)DateTime.Now.Ticks);
                watchs.Add(watachable, 0);
            }
        }

        public void RemoveWatchable(IWatchable watachable)
        {
            lock (watchs)
            {
                watchs.Remove(watachable);
            }
        }



    }
}
